# ============================================================================
# Table 5: Difference in support by source name (overall)
# ============================================================================

N <- nrow(data)
n_deandre <- sum(data$deandre)

diff_means_deandre <- mean(data$support_policy[data$deandre == 1]) -
  mean(data$support_policy[data$deandre == 0])
control_mean <- mean(data$support_policy[data$deandre == 0])
control_sd   <- sqrt(mean((data$support_policy[data$deandre == 0] - control_mean)^2))
set.seed(seed = 09291992, kind = "L'Ecuyer-CMRG")
Omega <- obtain_permutation_matrix(declaration = declare_ra(N = N,
                                                            m = n_deandre),
                                   maximum_permutations = n_sims)

null_dist <- sapply(X = 1:ncol(Omega),
                      FUN = function(x) { mean(data$support_policy[Omega[, x] == 1]) -
                          mean(data$support_policy[Omega[, x] == 0]) })
pval <- min(1, 2 * min(mean(null_dist <= diff_means_deandre), mean(null_dist >= diff_means_deandre)))

diff_str <- fmt(x = diff_means_deandre, digits = 4, pval = pval)
control_mean_str <- fmt(x = control_mean, digits = 4)
control_sd_str   <- fmt(x = control_sd, digits = 4)
pval_str <- fmt(x = pval, digits = 4)
N_str <- format_int(x = N)

table_5 <- sprintf(fmt = "\\caption{Estimated effect of Black source vs.~White source on policy support (pooled)}
\\centering 
\\begin{tabular}{@{\\extracolsep{5pt}}lc} 
\\\\[-1.8ex]\\hline 
\\hline \\\\[-1.8ex] 
 & \\multicolumn{1}{c}{\\textit{Dependent variable:}} \\\\ 
\\cline{1-2} 
\\\\[-1.8ex] & Policy Support \\\\ 
\\hline \\\\[-1.8ex] 
Black source cue & $%s$ \\\\ 
White source cue (control) mean & $%s$ \\\\ 
White source cue (control) SD & $%s$ \\\\ 
RI $p$-value (two-sided) & $%s$ \\\\ 
Number of observations & $%s$ \\\\ 
\\hline
\\hline \\\\[-1.8ex] 
\\textit{Note:} & $^{*}$p$<$0.1; $^{**}$p$<$0.05; $^{***}$p$<$0.01 
\\end{tabular}",
                   diff_str,
                   control_mean_str,
                   control_sd_str,
                   pval_str,
                   N_str)

writeLines(text = table_5, con = "code_and_output/tables/table_5.tex")

rm(list = setdiff(ls(), c("data", "fmt", "format_int", "n_sims")))
gc()